<template>
  <div class="container">
    <topTitle
      :titleText="`角色管理`"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <!-- <el-row class="topContent">
      <el-col :span="16">
        <div>
          <div class="contentTop">
            <p>
              <span class="titleText">
                <i class="icon iconfont iconfanhui1" @click="goBack"></i>
                角色管理
              </span>
            </p>
          </div>
        </div>
      </el-col>
    </el-row> -->
    <el-tabs
      v-model="activeName"
      type="card"
      @tab-click="handleClick"
      class="commonTab"
    >
      <el-tab-pane label="角色详情" name="first">
        <!-- 添加 -->
        <el-form
          v-if="type == 'add'"
          :model="formData"
          :rules="formRules"
          ref="formData"
          label-width="100px"
          class="demo-formData"
        >
          <el-row>
            <el-form-item
              prop="code"
              label="角色编码"
              class="row-padding-bottom"
            >
              <el-input
                v-model.trim="formData.code"
                placeholder="请填写角色编码"
                maxlength="20"
              ></el-input>
              <el-tooltip
                content="角色编码不支持修改"
                placement="top"
                effect="dark"
              >
                <i class="icon iconfont iconhuabanfuben"></i>
              </el-tooltip>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              prop="name"
              label="角色名称"
              class="row-padding-bottom"
            >
              <el-input
                v-model.trim="formData.name"
                placeholder="请输入角色名称"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="角色介绍" class="row-padding-bottom">
              <el-input
                type="textarea"
                v-model.trim="formData.remark"
                placeholder="请输入角色介绍"
                rows="4"
                maxlength="200"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-form-item>
            <el-button
              class="commonBut saveBtn"
              @click="saveToDetail"
              :loading="isSaveLoading"
              v-show="isShowAdd"
              >保存</el-button
            >
            <el-button class="commonBut" @click="goBack">取消</el-button>
          </el-form-item>
        </el-form>
        <!-- 修改 -->
        <el-form
          v-if="type == 'edit'"
          :model="formData"
          :rules="formRules"
          ref="formData"
          label-width="100px"
          class="demo-formData"
        >
          <el-row>
            <el-form-item
              prop="code"
              label="角色编码"
              class="row-padding-bottom"
            >
              <el-input
                v-model.trim="formData.code"
                :disabled="true"
                placeholder="请填写角色编码"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              prop="name"
              label="角色名称"
              class="row-padding-bottom"
            >
              <el-input
                v-model.trim="formData.name"
                placeholder="请输入角色名称"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="角色介绍" class="row-padding-bottom">
              <el-input
                type="textarea"
                v-model.trim="formData.remark"
                placeholder="请输入角色介绍"
                rows="4"
                maxlength="200"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-form-item>
            <el-button
              class="commonBut saveBtn"
              @click="saveToDetailE"
              :loading="isSaveLoading"
              v-show="isShowUpdate"
              >保存</el-button
            >
            <el-button class="commonBut" @click="cancleToDetail"
              >取消</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 详情 -->
        <div class="roleDetailBox" v-if="type == 'detail'">
          <el-row style="margin-bottom: 30px">
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont iconbianji"
              @click="roleEdit"
              v-show="isShowUpdate"
            >
              <span class="opetareText">修改</span>
            </el-button>
          </el-row>
          <el-row>
            <el-col :span="3" class="labelWidth">
              <div class="grid-content">角色ID：</div>
            </el-col>
            <el-col :span="20" class="information">
              <div class="grid-content">{{ this.roleInfo.id || '--' }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3" class="labelWidth">
              <div class="grid-content">角色编码：</div>
            </el-col>
            <el-col :span="20" class="information">
              <div class="grid-content">{{ this.roleInfo.code || '--' }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3" class="labelWidth">
              <div class="grid-content">角色名称：</div>
            </el-col>
            <el-col :span="20" class="information">
              <div class="grid-content">{{ this.roleInfo.name || '--' }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3" class="labelWidth">
              <div class="grid-content">角色介绍：</div>
            </el-col>
            <el-col :span="20" class="information">
              <div class="grid-content">{{ this.roleInfo.remark || '--' }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3" class="labelWidth">
              <div class="grid-content">角色所属用户：</div>
            </el-col>
            <el-col :span="20" class="information">
              <div class="grid-content">
                {{ this.roleInfo.creatorName || '--' }}
              </div>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="角色权限" name="second">
        <div class="roleQxBox">
          <el-row style="margin-bottom: 30px">
            <el-button
              v-if="qxOperateBtn === false && isShowUpdate"
              class="commonBut saveBtn funComBut"
              icon="icon iconfont iconbianji"
              @click="qxEdit"
            >
              <span class="opetareText">修改角色权限</span>
            </el-button>
          </el-row>
          <!-- <el-tree :data="treeData" ref="rootTree" :props="defaultProps" show-checkbox node-key="id" :default-checked-keys="checkIds" @check="clickDeal" :check-strictly="true" default-expand-all></el-tree> -->
          <div class="treeBox">
            <el-tree
              :default-expanded-keys="isOpenTree"
              :data="treeData"
              ref="rootTree"
              :props="defaultProps"
              show-checkbox
              node-key="id"
              :default-checked-keys="checkIds"
              :render-content="renderContent"
            ></el-tree>
          </div>

          <el-row style="margin-top: 30px" v-if="qxOperateBtn === true">
            <el-button
              class="commonBut saveBtn"
              @click="savaEditQx"
              :loading="isSaveLoading"
              >保存</el-button
            >
            <el-button class="commonBut" @click="cancelQx">取消</el-button>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="角色用户" name="thread">
        <!-- <div class="mainCon"> -->
        <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
          <el-form :inline="true" :model="filterField" class="el-form-thread">
            <el-col :lg="8" :xl="6">
              <el-form-item label="用户名" class="row-padding-bottom">
                <el-input
                  placeholder="请输入用户名"
                  clearable
                  v-model="filterField.username"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="姓名" class="row-padding-bottom">
                <el-input
                  placeholder="请输入姓名"
                  clearable
                  v-model="filterField.nickname"
                ></el-input>
              </el-form-item>
            </el-col>
            <template v-if="advanced">
              <el-col :lg="8" :xl="6">
                <el-form-item label="电话号码" class="row-padding-bottom">
                  <el-input
                    placeholder="请输入电话号码"
                    clearable
                    v-model="filterField.tel"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :lg="8" :xl="6">
                <el-form-item label="用户类型" class="row-padding-bottom">
                  <el-select
                    v-model="filterField.type"
                    placeholder="请选择"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in typeIds"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :lg="8" :xl="6">
                <el-form-item label="用户状态" class="row-padding-bottom">
                  <el-select
                    v-model="filterField.enabled"
                    placeholder="请选择"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in status"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
            <el-form-item>
              <a
                @click="toggleAdvanced"
                style="margin-left: 40px; color: #409eff; cursor: pointer"
                class="btnColor"
              >
                {{ advanced ? '收起' : '展开' }}
                <i
                  :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                ></i>
              </a>
              <el-button
                type="primary"
                icon="icon iconfont iconchazhao1"
                @click="searchList"
                class="searchBtn"
              >
                搜索
              </el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <div class="spacing"></div>
        <div
          ref="tableBox"
          :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
        >
          <el-table
            ref="tableBox1"
            :data="tableList"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            highlight-current-row
            v-loading="loading"
            stripe
            style="border: 1px solid #dfe6ec"
          >
            <el-table-column
              prop="username"
              label="用户名"
              align="center"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="nickname"
              label="姓名"
              align="center"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="phone"
              label="手机号"
              align="center"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="deptmentName"
              label="部门"
              align="center"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="typeDesc"
              label="用户类型"
              align="center"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="enabledDesc"
              label="状态"
              align="center"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              label="操作"
              align="center"
              :formatter="formatTd"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-link
                  type="primary"
                  v-hasBtn="'role:delete'"
                  @click="deltetRole(scope.row)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
            <!-- 表格数据为空时，页面显示 -->
            <div slot="empty" v-show="isShow">
              <emptyTable emptyText="暂无相关信息"></emptyTable>
            </div>
          </el-table>
          <Pagination
            ref="pagination"
            @getList="getTableList"
            :filterField="filterField"
            :requestUrl="requestUrl"
          ></Pagination>
        </div>
        <!-- </div> -->
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  name: 'roleManagerDetail',
  data() {
    return {
      filterField: {
        username: '',
        nickname: '',
        tel: '',
        type: '',
        enabled: '',
        roleId: '',
      },
      requestUrl: 'api-u/users/findByRole',
      tableList: [],
      loading: false,
      isShow: true,
      advanced: false,
      typeIds: [], //用户类型
      status: [], //用户状态

      titleText: '角色管理',
      back: true,
      activeName: 'first',
      isShowFirst: true,
      isShowSecond: false,
      type: '', //添加，修改，详情类型
      roleId: '', //当前角色id
      roleInfo: '', //当前角色信息
      isSaveLoading: false, // 保存loading
      formData: {
        code: '',
        name: '',
        remark: '',
      },
      formRules: {
        code: {
          required: true,
          pattern: /^[5A-Za-z0-9_]+$/,
          message: '请输入正确的角色编码',
          trigger: 'blur',
        },
        name: {
          required: true,
          message: '请输入角色名称',
          trigger: 'blur',
        },
      },
      defaultProps: {
        children: 'children',
        label: function (a, b) {
          if (a.remark != null) {
            return a.label + '(' + a.remark + ')'
          } else {
            return a.label
          }
        },
      },
      isOpenTree: [], //默认展开二级树
      qxOperateBtn: false,
      treeData: [],
      checkIds: [], //选中
      isShowUpdate: '',
      isShowAdd: '',
    }
  },
  created() {
    this.type = this.$route.query.type
    this.roleId = this.$route.query.roleId
    this.filterField.roleId = this.$route.query.roleId
    this.getTreeData('true')
    if (this.type === 'detail') {
      this.getRoleInfo(this.roleId)
    }
    if (this.type === 'qx') {
      this.type = 'detail'
      this.getRoleInfo(this.roleId)
      this.activeName = 'second'
    }
    this.isShowAdd = this.$store.state.buttonLimitsArr.indexOf('role:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('role:update') > -1
  },
  mounted() {
    $('.treeBox').height($('.mainCon').height() - 305)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.getUsertype()
    this.getUserstatus()
  },
  updated() {
    // 给多选树设置默认值
    this.$refs.rootTree.setCheckedKeys(this.checkIds)
  },
  methods: {
    getUsertype() {
      this.axios({
        method: 'post',
        url: 'api-u/users/usertype',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.typeIds = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getUserstatus() {
      this.axios({
        method: 'post',
        url: 'api-u/users/userstatus',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.status = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getTableList(data) {
      this.isShow = false
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      var that = this
      this.$nextTick(function () {
        that.$refs.pagination.getTableListData()
      })
    },
    deltetRole(item) {
      this.$confirm('确认删除该用户吗?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          console.log(item)
          this.axios
            .post('api-u/users/delrole', { id: item.id, roleId: this.roleId })
            .then((res) => {
              if (!res.data.hasError) {
                this.$message({
                  type: 'success',
                  message: '删除成功',
                })
                this.searchList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.errorMsg,
                })
              }
            })
        })
        .catch(() => {})
    },
    //开启loading
    openFullScreen() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      return loading
    },
    closeFullScreen(loading) {
      loading.close()
    },
    goBack() {
      this.$router.push({
        path: '/home/baseSettings/roleManager',
        name: 'roleManager',
      })
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/baseSettings/roleManager',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //tabs栏切换
    handleClick(tab, event) {},
    roleEdit() {
      this.type = 'edit'
      this.formData.code = this.roleInfo.code
      this.formData.name = this.roleInfo.name
      this.formData.remark = this.roleInfo.remark
    },
    //保存跳转到详情
    saveToDetail() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          this.roleAdd()
        } else {
          return false
        }
      })
    },
    saveToDetailE() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          this.roleEditSave()
        } else {
          return false
        }
      })
    },
    cancleToDetail() {
      this.type = 'detail'
    },
    roleAdd() {
      this.axios({
        method: 'post',
        url: 'api-u/role/add',
        data: this.formData,
      })
        .then((res) => {
          this.isSaveLoading = false
          if (!res.data.hasError) {
            this.$message({
              message: '添加成功',
              type: 'success',
            })
            setTimeout(() => {
              this.type = 'detail'
              this.roleId = res.data.result
              this.getRoleInfo(this.roleId)
            }, 200)
          } else {
            this.$message({
              type: 'error',
              message: res.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
        })
    },
    roleEditSave() {
      this.axios({
        method: 'post',
        url: '/api-u/role/edit',
        data: {
          id: this.roleId,
          name: this.formData.name,
          remark: this.formData.remark,
        },
      })
        .then((res) => {
          this.isSaveLoading = false
          if (!res.data.hasError) {
            this.$message({
              message: '修改成功',
              type: 'success',
            })
            setTimeout(() => {
              this.type = 'detail'
              this.getRoleInfo(this.roleId)
            }, 200)
          } else {
            this.$message({
              type: 'error',
              message: res.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
        })
    },
    getRoleInfo(roleId) {
      this.axios({
        method: 'post',
        url: '/api-u/role/detail',
        data: {
          id: roleId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.roleInfo = response.data.result
          } else {
            this.$message({
              type: 'error',
              message: res.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.$message.error('角色数据获取失败')
        })
    },
    getTreeData(isDisabled) {
      this.openFullScreen()
      this.axios({
        method: 'post',
        url: 'api-m/menus/initpermission',
        data: {
          roleId: this.roleId,
          disabled: isDisabled,
        },
      })
        .then((resp) => {
          this.checkIds = resp.data.result.checkIds
          this.treeData = resp.data.result.treeVOS
          this.closeFullScreen(this.openFullScreen())
          // 默认展开二级
          this.treeData.forEach((m) => {
            this.isOpenTree.push(m.id)
          })
        })
        .catch((error) => {
          this.closeFullScreen(this.openFullScreen())
        })
    },
    qxEdit() {
      this.qxOperateBtn = true
      this.getTreeData('false')
    },
    savaEditQx() {
      this.isSaveLoading = true
      var aKey = this.getCheckedKeys(
        this.treeData,
        this.$refs.rootTree.getCheckedKeys(),
        'id'
      )
      this.axios({
        method: 'post',
        url: 'api-u/role/setpermissions',
        data: {
          roleId: this.roleId,
          permissionList: aKey,
        },
      })
        .then((res) => {
          this.isSaveLoading = false
          if (!res.data.hasError) {
            this.$message({
              message: '修改成功',
              type: 'success',
            })
            setTimeout(() => {
              this.qxOperateBtn = false
              this.getTreeData('true')
            }, 200)
          } else {
            this.$message({
              type: 'error',
              message: res.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
        })
    },
    getCheckedKeys(data, keys, key) {
      var res = []
      recursion(data, false)
      return res
      // arr -> 树形总数据
      // keys -> getCheckedKeys获取到的选中key值
      // isChild -> 用来判断是否是子节点
      function recursion(arr, isChild) {
        var aCheck = []
        for (var i = 0; i < arr.length; i++) {
          var obj = arr[i]
          aCheck[i] = false
          if (obj.children) {
            aCheck[i] = recursion(obj.children, true) ? true : aCheck[i]
            if (aCheck[i]) {
              res.push(obj.type + ':' + obj[key])
            }
          }
          for (var j = 0; j < keys.length; j++) {
            if (obj[key] == keys[j]) {
              aCheck[i] = true
              if (res.indexOf(obj[key]) == -1) {
                res.push(obj.type + ':' + obj[key])
              }
              break
            }
          }
        }
        if (isChild) {
          return aCheck.indexOf(true) != -1
        }
      }
    },
    cancelQx() {
      this.qxOperateBtn = false
      this.getTreeData('true')
    },
    // 内容区渲染后执行 判断底层 赋 class
    renderContent(h, { node, data, store }) {
      let classname = ''
      if (node.level === 4) {
        classname = 'levelname'
      }

      // 由于项目中有二级菜单也有三级菜单，就要在此做出判断。
      if (node.level === 3 && node.childNodes.length === 0) {
        classname = 'levelname'
      }
      if (
        node.level === 4 ||
        (node.level === 3 && node.childNodes.length === 0)
      ) {
        this.$nextTick(function () {
          this.changeCss()
        })
      }
      return <p class={classname}>{node.label}</p>
    },
    changeCss() {
      var levelName = document.getElementsByClassName('levelname') // levelname是上面的最底层节点的名字
      for (var i = 0; i < levelName.length; i++) {
        // cssFloat 兼容 ie6-8  styleFloat 兼容ie9及标准浏览器
        levelName[i].parentNode.style.cssFloat = 'left' // 最底层的节点，包括多选框和名字都让他左浮动
        levelName[i].parentNode.style.styleFloat = 'left'
        // levelName[i].parentNode.style.paddingLeft = '0px'
      }
    },
  },
}
</script>

<style scoped lang="less">
// .mainCon {
//   top: 130px;
//   padding: 0;
/deep/ .el-form {
  padding: 50px 60px;
  .el-input__inner,
  textarea.el-textarea__inner {
    width: 340px;
    position: relative;
  }
}
.topContent {
  position: relative;
  background: #fff;
  height: 67px;
  padding: 20px 24px;
  .titleText {
    font: bold 18px Microsoft YaHei;
    color: #333;
    margin-bottom: 6px;
    line-height: 26px;
    .iconfanhui1 {
      font-size: 20px;
      margin-right: 6px;
      cursor: pointer;
    }
  }
  .alignRight {
    text-align: right;
  }
}
.roleDetailBox {
  padding: 50px 60px; // .labelWidth {
  .labelWidth {
    font-size: 14px;
    color: #666666;
    display: inline-block;
    height: 36px;
    text-align: right;
  }

  .information {
    font-size: 14px;
    color: #151515;
  }
  .grid-content {
    line-height: 36px;
  }
}
.roleQxBox {
  padding: 50px 60px;
}
i.el-tooltip.icon.iconfont.iconhuabanfuben {
  position: absolute;
  top: 0;
  left: 346px;
} // tab栏切换
.tabs {
  height: calc(100% - 67px);
  /deep/ .el-tabs__content {
    height: calc(100% - 40px);
    background-color: #fff;
    overflow-y: auto;
  }
}
// }

.treeBox {
  // height: 100px;
  overflow: auto;
}
.el-form-thread {
  padding: 24px 0 0 0 !important;
}
.searchBtn {
  padding: 9px 20px;
}
/deep/.searchInputWidth .el-input__inner {
  width: 230px !important;
}
</style>
